<?php

namespace App\Http\Controllers;

use App\Http\Model\QuestionNaireUser;
use App\Http\Model\User;
use App\Server\Helper;
use EasyWeChat\Support\Log;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;

class WechatController extends Controller
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        //Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $wechat = app('wechat');
        $this->menu($wechat); //设置菜单

        $userApi = $wechat->user; //用户信息
        $wechat->server->setMessageHandler(function($message) use ($userApi){
            switch ($message->MsgType)
            {
                case 'event':
                    # 事件消息...
                    break;
                case 'text':
                    # 文字消息...
                    return '你好 '.$userApi->get($message->FromUserName)->nickname;
                    break;
                case 'image':
                    # 图片消息...
                    break;
                case 'voice':
                    # 语音消息...
                    break;
                case 'video':
                    # 视频消息...
                    break;
                case 'location':
                    # 坐标消息...
                    break;
                case 'link':
                    # 链接消息...
                    break;
                // ... 其它消息
                default:
                    # code...
                    break;
            }
        });

        //Log::info('return response.');

        return $wechat->server->serve();
    }

    /**
     * 设置菜单
     * @param $wechat
     * create by wenQing
     */
    public function menu($wechat)
    {
        $menu = $wechat->menu;
        $buttons = [
            [
                "type" => "click",
                "name" => "今日歌曲",
                "key"  => "V1001_TODAY_MUSIC"
            ],
            [
                "name"       => "菜单",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "vwap",
                        "url"  => "http://vwap.haotoufa.com"
                    ],
                    [
                        "type" => "view",
                        "name" => "授权",
                        "url"  => "http://weixin.haotoufa.com/user"
                    ],
                    [
                        "type" => "view",
                        "name" => "微信首页",
                        "url"  => "http://weixin.haotoufa.com/index"
                    ],
                ],
            ],
        ];
        $menu->add($buttons);
    }

    /**
     * 用户授权界面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * create by wenQing
     */
    public function user(Request $request)
    {
        $userAuth = session('wechat.oauth_user'); // 拿到授权用户资料
        if($request->method() == 'POST')
        {
            $input = Input::all();
            //检测一下验证码是否正确
            if($input['post_code'] != $input['code'])
            {
                return back()->with('msg','验证码不正确，或者验证码超时！');
            }
            //检测通过，保存一下绑定信息
            $userModel = new User();
            $userModel->bindUser($input['mobile'],$userAuth->id,$userAuth->nickname,$userAuth->avatar,$userAuth->email,$userAuth->unionid);

            Helper::reflash();
        }
        else
        {
            $userArr = User::where('open_id',$userAuth->id)->get()->toArray();
            if($userArr)
            {
                //存在此open_id的用户，用户已经完成了微信的认证
                $user = $userArr[0]; //用户信息
                //微信用户登录
                $userModel = new User();
                $re = $userModel->login($user['username']);

                $seData = [
                    'u_id' => $user['id'],
                    'username' => $user['username'],
                    'nic_name' => $user['nic_name'],
                    'session_id' => $re['data']['session_id'],
                    'user_token' => $re['data']['user_token']
                ];
                $request->session()->put('user', $seData);
                $targetUrl = $request->session()->pull('target_url'); //获取session并且删除
                return redirect(url($targetUrl[0].'.html')); //跳转到首页
            }
            else
            {
                return view('user'); //绑定界面
            }
        }
    }

    public function test(Request $request)
    {
        $userAuth = session('wechat.oauth_user'); // 拿到授权用户资料
        if($request->method() == 'POST')
        {
            $input = Input::all();
            //检测一下验证码是否正确
            if($input['post_code'] != $input['code'])
            {
                return back()->with('msg','验证码不正确，或者验证码超时！');
            }
            //检测通过，保存一下绑定信息
            $userModel = new User();
            $userModel->bindUser($input['mobile'],'123123','123','123','123');

            Helper::reflash();
        }
        else
        {
            $userArr = User::where('open_id','123123')->get()->toArray();
            if($userArr)
            {
                //存在此open_id的用户，用户已经完成了微信的认证
                $user = $userArr[0]; //用户信息
                //微信用户登录
                $userModel = new User();
                $re = $userModel->login($user['username']);

                $seData = [
                    'u_id' => $user['id'],
                    'username' => $user['username'],
                    'nic_name' => $user['nic_name'],
                    'session_id' => $re['data']['session_id'],
                    'user_token' => $re['data']['user_token']
                ];
                $request->session()->put('user', $seData);

                //$value = $request->session()->get('user', 'default');
                return redirect(url('index')); //跳转到首页
            }
            else
            {
                return view('test'); //绑定界面
            }
        }
    }

    public function test2()
    {
        $re = QuestionNaireUser::where('cash_id',2)->where('u_id',1)->first();
        $time = time() - strtotime($re->created_at);
        if($time < 60)
        {
            $time_str = $time.'秒';
        }
        elseif(($time/60) < 60)
        {
            $time_str = (int)($time/60).'分';
        }
        elseif(($time/60/60) < 60)
        {
            $time_str = (int)($time/60/60).'时';
        }
        elseif(($time/60/60/24) < 60)
        {
            $time_str = (int)($time/60/60/24).'天';
        }
        dd((int)($time/60/60/24));
        return redirect('test3')->with('test','test3');
    }

    public function test3(Request $request)
    {
        dump(session('test'));
        echo '333333';
    }
}
